package cn.codexin.wechatofficial.service;

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ly
 * @date 2020/9/21 0021 15:29
 * 用来判断遥测数据中值的状态
 */
@Service
public class MVStatusService {

    public Object convertToCode(String jexlExp, Map<String,Object> map){
        JexlEngine jexl=new JexlEngine();
        Expression e = jexl.createExpression(jexlExp);
        JexlContext jc = new MapContext();
        for(String key:map.keySet()){
            jc.set(key, map.get(key));
        }
        if(null==e.evaluate(jc)){
            return "";
        }
        return e.evaluate(jc);
    }

    public String status(String ValuesMap,float value) {
        String status = "";  //需要返回的状态判断
        if (ValuesMap==null)
            return status;
        Boolean isTrue;
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("value",value);   //赋值value

        String[] temp1; //外层遍历，分为多个状态
        String[] temp2; //内层遍历，分为三个字段，分别是两个判断段和一个状态段

        String str; //总判断语句
        String split1 = ";";    // 指定分割字符1
        String split2 = ",";    // 指定分割字符2
        temp1 = ValuesMap.split(split1); // 分割外层字符串
        // 开始遍历和处理
        try {
            for(int i =0; i < temp1.length ; i++){
                temp2 = temp1[i].split(split2);
                if(temp2[0].indexOf("=")==1&&temp2[0].substring(0,1).equals(" "))
                    temp2[0] = "="+temp2[0];
                if(temp2[1].indexOf("=")==1&&temp2[1].substring(0,1).equals(" "))
                    temp2[1] = "="+temp2[1];
                str = "value"+temp2[0]+"&&value"+temp2[1];

                str = str.replaceAll(" ", "");

                isTrue = (Boolean)convertToCode(str,map);
                if (isTrue) {
                    status = temp2[2];
                    return status;
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return status;
    }
}
